import React from 'react'

var Button = component('Button')
var Grid = component('Grid')
var PerfectName = component('PerfectName')
var PerfectBonus = model('PerfectBonus');

var blinAduio = require('../../Resource/sound/blinblin.mp3');

module.exports = React.createClass({
  getInitialState: function() {
    return {
      data: new Array(10),
      step: {
        name: '',
        count: 0
      },
      show: 0
    };
  },
  componentDidMount() {
    var step = PerfectBonus.getStep();
    var data = PerfectBonus.getCurrentPickPack();
    var show = false;
    
    // 这轮抽过的重刷默认选中
    if (data.length > 0 && PerfectBonus.getPrepare() == 2) {
      data.map(v=>{
        v.show = true;
        return v;
      });
      show = true;
    }

    // 开始抽奖
    if (step.index == 0 && data.length == 0) {
      data = (function(){var d=[];for(var i=0;i<10;i++){d[i]=i;}return d;})();
      show = false;
    }

    if (step.completed) data = [];
    this.setState({data:data, step: step, show: show});
  },
  cellRender(data){
    return <PerfectName show={data.show}>{data.name}</PerfectName>
  },
  getHappy(){
    if(this.showing) return;
    var step = PerfectBonus.getStep();
    if (step.completed) return;
    if (step.index == 0){
      PerfectBonus.pick();
    }
    var data = PerfectBonus.getCurrentPickPack();
    this.show(data);
    PerfectBonus.setPrepare(2);
  },
  showing: false,
  show(data){
    this.showing = true;
    setTimeout((function(){
      global.blin = this.refs.blin;
      this.refs.blin.pause();
      this.refs.blin.src = blinAduio;
      this.refs.blin.play();
      var l = data.filter(v=>{return !v.show;}).length;
      if (l>0){
        data[data.length-l].show = true;
        this.setState({data:data});
        this.show(data);
        this.showing = true;
      } else {
        this.showing = false;
        this.setState({show:true});
      }
    }).bind(this), 800);
  },
  print(){
    global.print();
  },
  next(){
    PerfectBonus.nextStep();
    PerfectBonus.pick();
    PerfectBonus.setPrepare(1);
    var data = PerfectBonus.getCurrentPickPack();
    this.setState({show: false, data: data, step: PerfectBonus.getStep()});
  },
  render(){
    return (
      <div className={global.baseStyle.body}>
        <Grid col={5} data={this.state.data} cellRender={this.cellRender} />
        {this.state.data.length==0 ? <div style={{height: 200}}></div> : ''}
        {this.state.show ? <div style={{textAlign:'center'}}>
            <Button type="happy" onClick={this.next}>{this.state.step.name}已诞生</Button>
          </div> :
        <div style={{textAlign:'center'}}><audio ref="blin" src={blinAduio}/><Button type="happy" onClick={this.getHappy}>{this.state.step.name}</Button></div>}
      </div>
    );
  }
});